package top.wineye.spring.ioc.dependency;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;
import top.wineye.model.UserContainer;

public class DependencyInject {

    /*
        依赖的注入

     */

    public static void main(String[] args) {
        BeanFactory bf =
                new ClassPathXmlApplicationContext("classpath:META-INF/dependency-inject-context.xml");

        // bean 来源一： 自定义 bean
        UserContainer uc = bf.getBean(UserContainer.class);
        System.out.println(uc.getUsers());

        // bean 来源二： 内建依赖 非 bean
        // 下面这行报错 No qualifying bean of type 'org.springframework.beans.factory.BeanFactory' available
        // BeanFactory bean = bf.getBean(BeanFactory.class);
        BeanFactory beanFactory = uc.getBeanFactory();
        System.out.println("auto wired beanFactory: " + beanFactory);

        System.out.println("auto wired beanFactory is the one we're using ? ["+ (bf == beanFactory) + "]");

/*        ObjectFactory<User> objectFactory = uc.getObjectFactory();
        User u = objectFactory.getObject();
        System.out.println("user from objectFactory" + u);*/
        ObjectFactory<ApplicationContext> objectFactory = uc.getObjectFactory();
        ApplicationContext applicationContext = objectFactory.getObject();
        System.out.println("the applicationContext get from objectFactory: " + applicationContext);
        System.out.println(bf == applicationContext);

        // bean 来源三：容器内建 bean
        Environment env = bf.getBean(Environment.class);
        System.out.println("通过 getBean 获取到的 Environment 对象：" + env);
    }
}
